<template>
    <view>
        <!-- pages/order/order.wxml -->
        <view class="order-container">
            <!-- 自定义导航栏 -->
            <custom-navbar title="订单列表" backgroundColor="#ffffff" textColor="#000" :showBack="true"
                :isHomePage="false"></custom-navbar>

            <!-- 订单类型，1、房间订单 2、商品订单 -->
            <!-- 订单类型切换 -->
            <view class="order-type-section">
                <up-tabs :current="orderType" :list="orderTypeTabs" @change="onOrderTypeChange"></up-tabs>
            </view>
            
            <!-- 状态标签 -->
            <view class="tabs-section">
                <up-tabs :current="activeTab" :list="statusTabs" @change="onTabChange"></up-tabs>
            </view>

            <!-- 订单列表 -->
            <view class="orders-section">
				<u-loading-page :loading="loading" loading-text="loading..."></u-loading-page>
                <scroll-view v-if="!loading" scroll-y="true" :style="{ height: availableHeight + 'px' }" class="orders-scroll-view">
                    <!-- 房间订单容器 -->
                    <view v-if="orderType === 0" class="room-orders-container">
                        <view class="orders-section-list">
                            <view class="order-item" :data-item="item" v-for="(item, index) in orders" :key="index" @click="goToOrderDetail(item)">
                                <!-- 订单头部 -->
                                <view class="order-item-header">
                                    <view class="order-item-header-info">
                                        <text class="order-item-header-info-time">订单编号：{{ item.sn }}</text>
                                        <up-tag text="待支付" plain size="mini" type="warning" v-if="item.pay_status === 0"></up-tag>
                                        <up-tag text="待入住" plain size="mini" type="warning" v-if="item.pay_status === 1 && item.is_used === 0"></up-tag>
                                        <up-tag text="已取消" plain size="mini" type="warning" v-if="item.pay_status === 2"></up-tag>
                                        <up-tag text="已入住" plain size="mini" type="warning" v-if="item.is_used === 1"></up-tag>
                                        <up-tag text="已退款" plain size="mini" type="warning" v-if="item.refund_status === 1"></up-tag>
                                    </view>
                                </view>

                                <view class="order-item-content">
                                    <view class="order-item-content-left">
                                        <image :src="item.roomInfo.cover || ''" mode="" />
                                    </view>
                                    <view class="order-item-content-right">
                                        <view class="order-item-content-right-title">{{ item.roomInfo.name }}</view>
                                        <view class="order-item-content-right-tips">1房·可住两人·一床</view>
                                        <view class="order-item-content-right-tips">{{ item.start_date }}入住 {{ item.end_date }}离店</view>
                                    </view>
                                </view>

                                <view class="order-item-footer">
                                    <view class="order-item-footer-left">
                                        <text>在线支付</text>
                                        <text>￥{{ item.order_amount }}</text>
                                    </view>
                                    <view class="order-item-footer-right">
                                        <up-button color="rgba(57, 97, 54, 1)" round v-if="item.pay_status === 0" @tap.native="payOrder(item)" :customStyle="customStyle">立即支付</up-button>
                                        <up-button color="rgba(57, 97, 54, 1)" round plain v-if="item.pay_status === 0" @tap.native="cancelOrder(item)" :customStyle="customStyle">取消订单</up-button>
                                        <up-button type="error" round plain v-if="item.pay_status === 1 && item.is_used == 0 && item.is_disable_refund == 1" @tap.native="refundOrder(item)" :customStyle="customStyle">退款</up-button>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>

                    <!-- 商品订单容器 -->
                    <view v-else class="shop-orders-container">
                        <view class="orders-section-list">
                            <view class="order-item" :data-item="item" v-for="(item, index) in orders" :key="index" @click="goToOrderDetail(item)">
                                <!-- 订单头部 -->
                                <view class="order-item-header">
                                    <view class="order-item-header-info">
                                        <text class="order-item-header-info-time">订单编号：{{ item.sn }}</text>
                                        <up-tag text="待支付" plain size="mini" type="warning" v-if="item.pay_status === 0"></up-tag>
                                        <up-tag text="待发货" plain size="mini" type="warning" v-if="item.pay_status === 1 && item.status === 0"></up-tag>
                                        <up-tag text="待收货" plain size="mini" type="warning" v-if="item.pay_status === 1 && item.status === 1"></up-tag>
                                        <up-tag text="已完成" plain size="mini" type="success" v-if="item.pay_status === 1 && item.status === 2"></up-tag>
                                        <up-tag text="已退款" plain size="mini" type="warning" v-if="item.refund_status === 1"></up-tag>
                                    </view>
                                </view>

                                <view class="order-item-content">
                                    <view class="order-item-content-left">
                                        <image v-if="item.goods_list && item.goods_list.length > 0 && item.goods_list[0].image && item.goods_list[0].image.length > 0" :src="item.goods_list[0].image[0]" mode="" />
                                    </view>
                                    <view class="order-item-content-right">
                                        <view class="order-item-content-right-title">{{ item.productInfo?.name || item.product_name }}</view>
                                        <view class="order-item-content-right-tips">数量：{{ item.quantity || 1 }}件</view>
                                        <view class="order-item-content-right-tips">下单时间：{{ item.created_at || item.order_time }}</view>
                                    </view>
                                </view>

                                <view class="order-item-footer">
                                    <view class="order-item-footer-left">
                                        <text>在线支付</text>
                                        <text>￥{{ item.order_amount }}</text>
                                    </view>
                                    <view class="order-item-footer-right">
                                        <up-button color="rgba(57, 97, 54, 1)" round v-if="item.pay_status === 0" @tap.native="payShopOrder(item)" :customStyle="customStyle">立即支付</up-button>
                                        <up-button color="rgba(57, 97, 54, 1)" round plain v-if="item.pay_status === 0" @tap.native="cancelShopOrder(item)" :customStyle="customStyle">取消订单</up-button>
                                        <!-- <up-button type="primary" round plain v-if="item.pay_status === 1 && item.status === 1" @tap.native="confirmReceive(item)" :customStyle="customStyle">确认收货</up-button> -->
                                        <up-button type="error" round plain v-if="item.pay_status === 1 && item.is_disable_refund === 1" @tap.native="refundShopOrder(item)" :customStyle="customStyle">申请退款</up-button>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>

                    <!-- 空状态 -->
                    <up-empty v-if="!loading && orders.length === 0" description="暂无订单" />
                </scroll-view>
            </view>
        </view>

        <up-toast id="up-toast" />
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick, computed } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue'
import { orderListFun, payFun, orderGoodsListFun } from '@/api/port'


const customStyle = reactive({
    width: '160rpx',
    height: '100%',
    margin: '0'
})

// 响应式数据
const orderType = ref<number>(0)
const orderTypeTabs = ref<any[]>([
    {
        name: '房间订单'
    },
    {
        name: '商品订单'
    }
])
const activeTab = ref<number>(0)
const statusTabs = ref<any[]>([
    {
        name: '全部',
        value: 0
    },
    {
        name: '待付款',
        value: 1
    },
    {
        name: '待入住',
        value: 2
    },
    {
        name: '已入住',
        value: 3
    },
    {
        name: '已退款',
        value: 4
    }
])
const orders = ref<any[]>([])  
const loading = ref<boolean>(false)
const scrollViewHeight = ref<number>(0)

// 方法定义
const onOrderTypeChange = (event: any): void => {
    console.log('onOrderTypeChange', event)
    const { index } = event
    orderType.value = index
    // 切换订单类型时重置状态筛选为全部
    activeTab.value = 0
    if(index == 0){
        statusTabs.value = [
            {
                name: '全部',
                value: 0
            },
            {
                name: '待付款',
                value: 1
            },
            {
                name: '待入住',
                value: 2
            },
            {
                name: '已入住',
                value: 3
            },
            {
                name: '已退款',
                value: 4
            }
        ]
        getOrderList()
    }else{
        statusTabs.value = [
            {
                name: '全部',
                value: 0
            },
            {
                name: '待付款',
                value: 1
            },
            {
                name: '已支付',
                value: 2
            },
            {
                name: '已退款',
                value: 4
            }
        ]
        getShopOrderList()
    }
}

const onTabChange = (event: any): void => {
    console.log('onTabChange', event)
    const { value } = event
    activeTab.value = value
    getOrderList()
}



const goToOrderDetail = (event?: any): void => {
    if (event) {
        const { id } = event
        if(orderType.value === 0){
            uni.navigateTo({
                url: `/subpackage/orderDetail/orderDetail?id=${id}`
            })
        }else{
            uni.navigateTo({
                url: `/subpackage/shopOrderDetail/shopOrderDetail?id=${id}`
            })
        }
    } 
}

const payOrder = (order: any): void => {
    const { id } = order
    uni.showModal({
        title: '确认支付',
        content: '确定要支付这个订单吗？',
        success: (res: any) => {
            if (res.confirm && id) {
                processPayment(id)
            }
        }
    })
}

// 商品订单支付
const payShopOrder = (order: any): void => {
    const { id } = order
    uni.navigateTo({
        url: `/subpackage/shopPayPage/shopPayPage?orderId=${id}&totalAmount=${order.order_amount}`
    })
}

// 取消商品订单
const cancelShopOrder = (order: any): void => {
    uni.showModal({
        title: '取消订单',
        content: '确定要取消这个订单吗？',
        success: (res: any) => {
            if (res.confirm) {
                // 调用取消订单API
                uni.showToast({
                    title: '订单已取消',
                    icon: 'success'
                })
                getOrderList()
            }
        }
    })
}

// 确认收货
const confirmReceive = (order: any): void => {
    uni.showModal({
        title: '确认收货',
        content: '确定已收到商品吗？',
        success: (res: any) => {
            if (res.confirm) {
                // 调用确认收货API
                uni.showToast({
                    title: '确认收货成功',
                    icon: 'success'
                })
                getOrderList()
            }
        }
    })
}

// 申请退款
const refundShopOrder = (order: any): void => {
    uni.showModal({
        title: '申请退款',
        content: '确定要申请退款吗？',
        success: (res: any) => {
            if (res.confirm) {
                // 调用申请退款API
                uni.showToast({
                    title: '退款申请已提交',
                    icon: 'success'
                })
                getOrderList()
            }
        }
    })
}

// 取消房间订单
const cancelOrder = (order: any): void => {
    uni.showModal({
        title: '取消订单',
        content: '确定要取消这个订单吗？',
        success: (res: any) => {
            if (res.confirm) {
                // 调用取消订单API
                uni.showToast({
                    title: '订单已取消',
                    icon: 'success'
                })
                getOrderList()
            }
        }
    })
}

// 房间订单退款
const refundOrder = (order: any): void => {
    uni.showModal({
        title: '申请退款',
        content: '确定要申请退款吗？',
        success: (res: any) => {
            if (res.confirm) {
                // 调用申请退款API
                uni.showToast({
                    title: '退款申请已提交',
                    icon: 'success'
                })
                getOrderList()
            }
        }
    })
}

const processPayment = async (orderId: number): void => {
    uni.showLoading({
        title: '支付中...'
    })
    await requestWeChatPay(orderId)
    uni.hideLoading()
    uni.showToast({
        title: '支付成功',
        icon: 'success'
    })
    getOrderList()
}

// 调用微信支付
const requestWeChatPay = async (orderId: any): Promise<any> => {
    try {
        // 这里应该调用后端API获取支付参数
        // 模拟获取支付参数
        const res = await payFun({ order_id: orderId, from: 'order', pay_way: '2' })
        console.log('res', res)
        const paymentParams: PaymentParams = {
            timeStamp: res.data.config.timeStamp,
            nonceStr: res.data.config.nonceStr,
            package: res.data.config.package,
            signType: res.data.config.signType,
            paySign: res.data.config.paySign
        }

        // 调用微信支付API
        return new Promise((resolve, reject) => {
            uni.requestPayment({
                ...paymentParams,
                success: (res: any) => {
                    console.log('支付成功:', res)
                    resolve(res)
                },
                fail: (err: any) => {
                    console.error('支付失败:', err)
                    uni.hideLoading()
                    
                    if (err.errMsg === 'requestPayment:fail cancel') {
                        reject(new Error('用户取消支付'))
                        uni.showToast({
                            title: '用户取消支付',
                            icon: 'error'
                        })
                    } else {
                        uni.showToast({
                            title: '支付失败',
                            icon: 'error'
                        })
                        reject(new Error('支付失败: ' + err.errMsg))
                    }
                }
            })
        })
    } catch (error) {
        console.log('CatchClause', error)
        console.error('请求支付失败:', error)
        throw error
    }
}


// 获取订单列表
const getOrderList = async (): Promise<void> => {
    loading.value = true
    try {
        const params = {
            page_no: 1,
            order_status: activeTab.value // 1为房间订单，2为商品订单
        }
        const res = await orderListFun(params)
        if (res.code === 1) {
            orders.value = res.data.list
        }
    } catch (error) {
        console.error('获取订单列表失败:', error)
    } finally {
        loading.value = false
    }
}
// 获取订单列表
const getShopOrderList = async (): Promise<void> => {
    loading.value = true
    try {
        const params = {
            page_no: 1,
            order_status: activeTab.value // 1为房间订单，2为商品订单
        }
        const res = await orderGoodsListFun(params)
        if (res.code === 1) {
            orders.value = res.data.list
        }
    } catch (error) {
        console.error('获取订单列表失败:', error)
    } finally {
        loading.value = false
    }
}
// 计算scroll-view高度
const windowInfo = uni.getWindowInfo()
const navbarHeight = uni.getStorageSync('navbarHeight') || 88
const orderTypeHeight = ref(0)
const tabsHeight = ref(0)
const calculateScrollViewHeight = async (): void => {
    
    await nextTick(() => {
		let timer = setTimeout(() => {
            // 获取 view class 的高度
            const query = uni.createSelectorQuery();
            query.select('.order-type-section').boundingClientRect((data) => {
                if (data) {
                    orderTypeHeight.value = data.height;
                }
            }).exec();
            query.select('.tabs-section').boundingClientRect((data) => {
                if (data) {
                    tabsHeight.value = data.height;
                }
            }).exec();
            clearTimeout(timer);
        }, 500)
    })
    // await computeScrollViewHeight(windowInfo.screenHeight, navbarHeight, orderTypeHeight.value, tabsHeight.value)
    // console.log(windowInfo.screenHeight, navbarHeight, orderTypeHeight.value, tabsHeight.value)
    
}

const computeScrollViewHeight = async (windowInfoHeight: number, navbarHeight: number, orderTypeHeight: number, tabsHeight: number) => {
    // console.log('computeScrollViewHeight', windowInfoHeight, navbarHeight, orderTypeHeight, tabsHeight)
    // scrollViewHeight.value = 
}
const availableHeight = computed((): number => {
    console.log(windowInfo)
    console.log('我进来了')
	// console.log(windowHeight.value, navbarTotalHeight.value, submitBarHeight.value, windowHeight.value - navbarTotalHeight.value - submitBarHeight.value);
	return windowInfo.screenHeight - navbarHeight - orderTypeHeight.value - tabsHeight.value - 40;
});
// 生命周期钩子
onMounted(() => {
    calculateScrollViewHeight()
    getOrderList()
})

</script>
<style>
/* pages/order/order.wxss */
.order-container {
    background-color: #f7f8fa;
    min-height: 100vh;
}

.order-type-section {
    background-color: #fff;
    border-bottom: 1px solid #ebedf0;
}

.tabs-section {
    background-color: #fff;
    border-bottom: 1px solid #ebedf0;
}

.orders-section {
    padding: 24rpx;
}

.orders-scroll-view {
    width: 100%;
}

.room-orders-container,
.shop-orders-container {
    width: 100%;
}

.order-item {
    background-color: #fff;
    padding: 20rpx 25rpx;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.order-item-header {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    padding: 24rpx 0;
    border-bottom: 1px solid #ebedf0;
}

.order-item-header-info {
    width: 100%;
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 8rpx;
}

.order-item-header-info-time {
    font-size: 24rpx;
    color: #969799;
}

.order-item-header-info-tag {
    margin-left: 24rpx;
    font-size: 20rpx !important;
}

.order-item-header-status {
    font-size: 28rpx;
    font-weight: 500;
    color: #1989fa;
    letter-spacing: 0px;
}

/* 加载状态 */
.up-loading {
    display: flex;
    justify-content: center;
    padding: 80rpx 0;
}

/* 自定义Vant组件样式 */
.up-nav-bar {
    background-color: #fff;
}

.up-tabs__line {
    background-color: #1989fa;
}

.up-button--small {
    font-size: 24rpx;
    padding: 12rpx 24rpx;
}

.up-empty {
    padding: 120rpx 0;
}

.up-image {
    border-radius: 12rpx;
}

.order-item-content {
    width: 100%;
    display: flex;
    align-items: flex-start;
    padding: 25rpx 0;
    box-sizing: border-box;
}

.order-item-content-left {
    width: 194rpx;
    height: 168rpx;
}

.order-item-content-left image {
    width: 100%;
    height: 100%;
}

.order-item-content-right {
    width: calc(100% - 194rpx - 24rpx);
    margin-left: 24rpx;
}

.order-item-content-right .order-item-content-right-title {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: bold;
    letter-spacing: 0px;
    line-height: 37.13rpx;
    color: rgba(19, 19, 19, 1);
    margin-bottom: 24rpx;
}

.order-item-content-right .order-item-content-right-tips {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 31.82rpx;
    color: rgba(19, 19, 19, 0.6);
    margin-bottom: 12rpx;
}

.order-item-footer {
    width: 100%;
    padding: 20rpx 0;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid #ebedf0;
}

.order-item-footer .order-item-footer_left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.order-item-footer .order-item-footer-left text:nth-child(1) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 34.75rpx;
    color: rgba(153, 153, 153, 1);
}

.order-item-footer .order-item-footer-left text:nth-child(2) {
    /** 文本1 */
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 42.43rpx;
    color: rgba(19, 19, 19, 1);
    margin-left: 12rpx;
}

.order-item-footer .order-item-footer-right {
    /* width: 208rpx; */
    flex: 1;
    height: 65rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 0 20rpx;
    margin-left: 20rpx;
}

.order-item-footer .order-item-footer-right .btn {
    width: 100%;
    max-width: 250rpx;
    height: 100%;
    margin: 0 !important;
}
</style>
